package com.atguigu.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.cloud.entity.Storage;
import com.atguigu.cloud.service.StorageService;
import com.atguigu.cloud.mapper.StorageMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author fafa
* @description 针对表【t_storage】的数据库操作Service实现
* @createDate 2024-06-26 21:31:04
*/
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage>
    implements StorageService{

    @Resource
    private StorageMapper storageMapper;


    @Override
    public boolean decrease(Long productId, Integer count) {

        //模拟超时订单
        //myTimeOut();

        LambdaQueryWrapper<Storage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Storage::getProductId,productId);

        Storage storage = storageMapper.selectOne(queryWrapper);


        if(storage == null){
            return false;
        }
        if(storage.getResidue() < count){
            //没有可用库存了
            return false;
        }
        storage.setResidue(storage.getResidue() - count);
        storage.setUsed(storage.getUsed() + count);


        storageMapper.updateById(storage);
        return true;

    }


    private static void myTimeOut()
    {
        try { TimeUnit.SECONDS.sleep(65); } catch (InterruptedException e) { e.printStackTrace(); }
    }

}




